import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage, AIMessage, SystemMessage, BaseMessage, ToolMessage } from "@langchain/core/messages";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { getDatabase } from "../database/init";
import { v4 as uuidv4 } from 'uuid';
import { normalizeTimestamp, normalizeDueDate } from "../utils/dateUtils";

// 聊天模型配置
export class LangChainService {
  private chatModel: ChatOpenAI;
  private modelWithTools: any;
  private db: any;
  private tools: any[] = [];
  private currentUserId?: string;

  constructor() {
    this.db = getDatabase();
    // 初始化聊天模型
    this.chatModel = new ChatOpenAI({
      openAIApiKey: process.env.OPENAI_API_KEY,
      configuration: {
        baseURL: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1'
      },
      modelName: process.env.OPENAI_MODEL || 'gpt-3.5-turbo',
      temperature: 0.7,
      maxTokens: 1000,
      streaming: true
    });

    // 初始化工具
    this.initializeTools();
  }

  // 初始化工具
  private initializeTools() {
    this.tools = [
      this.createTaskTool(),
      this.updateTaskTool(),
      this.queryTasksTool(),
      this.completeTaskTool(),
      this.deleteTaskTool(),
      this.getTaskStatsTool()
    ];

    this.modelWithTools = this.chatModel.bindTools(this.tools);
  }

  // 创建任务工具
  private createTaskTool() {
    return tool(
      async (input: any) => {
        const { title, description, priority, dueDate, category, tags } = input;
        try {
          console.log(`[LangChain] 创建任务: ${title}`);
          
          const taskId = uuidv4();
          const now = new Date();
          
          const result = await this.db.query(`
            INSERT INTO tasks (id, title, description, priority, due_date, category, tags, status, completed, created_at, updated_at, user_id)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
            RETURNING *
          `, [
            taskId,
            title,
            description || '',
            priority || 'P2',
            dueDate ? normalizeDueDate(dueDate) : null,
            category || 'work',
            JSON.stringify(tags || []),
            'todo',
            false,
            normalizeTimestamp(now),
            normalizeTimestamp(now),
            'default-user' // 在实际应用中应该从上下文获取
          ]);

          const task = result.rows[0];
          
          return JSON.stringify({
            success: true,
            data: task,
            message: `已创建任务"${title}"，优先级：${task.priority}`
          });
        } catch (error) {
          console.error('[LangChain] 创建任务失败:', error);
          return JSON.stringify({
            success: false,
            error: error instanceof Error ? error.message : '创建任务失败'
          });
        }
      },
      {
        name: "create_task",
        description: "创建新任务",
        schema: z.object({
          title: z.string().describe("任务标题"),
          description: z.string().optional().describe("任务描述"),
          priority: z.enum(["P0", "P1", "P2", "P3"]).optional().describe("任务优先级"),
          dueDate: z.string().optional().describe("截止日期"),
          category: z.string().optional().describe("任务分类"),
          tags: z.array(z.string()).optional().describe("任务标签")
        })
      }
    );
  }

  // 更新任务工具
  private updateTaskTool() {
    return tool(
      async (input: any) => {
        const { taskId, updates } = input;
        try {
          console.log(`[LangChain] 更新任务: ${taskId}`);
          
          const updateFields = [];
          const values = [];
          let paramIndex = 1;

          if (updates.title) {
            updateFields.push(`title = $${paramIndex++}`);
            values.push(updates.title);
          }
          if (updates.description !== undefined) {
            updateFields.push(`description = $${paramIndex++}`);
            values.push(updates.description);
          }
          if (updates.priority) {
            updateFields.push(`priority = $${paramIndex++}`);
            values.push(updates.priority);
          }
          if (updates.status) {
            updateFields.push(`status = $${paramIndex++}`);
            values.push(updates.status);
          }
          if (updates.dueDate !== undefined) {
            updateFields.push(`due_date = $${paramIndex++}`);
            values.push(updates.dueDate ? normalizeDueDate(updates.dueDate) : null);
          }
          if (updates.category) {
            updateFields.push(`category = $${paramIndex++}`);
            values.push(updates.category);
          }
          if (updates.tags) {
            updateFields.push(`tags = $${paramIndex++}`);
            values.push(JSON.stringify(updates.tags));
          }

          if (updateFields.length === 0) {
            return JSON.stringify({
              success: false,
              error: '没有提供要更新的字段'
            });
          }

          updateFields.push(`updated_at = $${paramIndex++}`);
          values.push(normalizeTimestamp(new Date()));
          values.push(taskId);

          const result = await this.db.query(`
            UPDATE tasks 
            SET ${updateFields.join(', ')}
            WHERE id = $${paramIndex}
            RETURNING *
          `, values);

          if (result.rows.length === 0) {
            return JSON.stringify({
              success: false,
              error: '任务不存在'
            });
          }

          const task = result.rows[0];
          
          return JSON.stringify({
            success: true,
            data: task,
            message: `已更新任务"${task.title}"`
          });
        } catch (error) {
          console.error('[LangChain] 更新任务失败:', error);
          return JSON.stringify({
            success: false,
            error: error instanceof Error ? error.message : '更新任务失败'
          });
        }
      },
      {
        name: "update_task",
        description: "更新现有任务",
        schema: z.object({
          taskId: z.string().describe("任务ID"),
          updates: z.object({
            title: z.string().optional(),
            description: z.string().optional(),
            priority: z.enum(["P0", "P1", "P2", "P3"]).optional(),
            status: z.enum(["todo", "in_progress", "review", "done"]).optional(),
            dueDate: z.string().optional(),
            category: z.string().optional(),
            tags: z.array(z.string()).optional()
          }).describe("要更新的字段")
        })
      }
    );
  }

  // 查询任务工具 (真实数据库查询)
  private queryTasksTool() {
    return tool(
      async (input: any) => {
        try {
          console.log('[LangChain] 🔍 查询任务工具被调用');
          console.log('[LangChain] 📥 输入参数:', JSON.stringify(input, null, 2));
          
          // 解析输入参数
          const filters = input.filters || {};
          const {
            status,
            priority,
            category,
            tags,
            dueDate,
            completed
          } = filters;
          
          const {
            sortBy = 'created_at',
            limit = 20
          } = input;
          
          // 构建查询条件
          const conditions = ['t.user_id = $1'];
          const values = [this.currentUserId || 'anonymous'];
          let paramIndex = 2;
          
          if (status) {
            conditions.push(`t.status = $${paramIndex}`);
            values.push(status);
            paramIndex++;
          }
          
          if (priority) {
            conditions.push(`t.priority = $${paramIndex}`);
            values.push(priority);
            paramIndex++;
          }
          
          if (category) {
            conditions.push(`t.category = $${paramIndex}`);
            values.push(category);
            paramIndex++;
          }
          
          if (completed !== undefined) {
            conditions.push(`t.completed = $${paramIndex}`);
            values.push(completed);
            paramIndex++;
          }
          
          if (tags && Array.isArray(tags) && tags.length > 0) {
            conditions.push(`t.tags && $${paramIndex}`);
            values.push(tags as any);
            paramIndex++;
          }
          
          if (dueDate) {
            // 支持日期范围查询，格式: "2024-01-01" 或 "2024-01-01,2024-01-31"
            if (dueDate.includes(',')) {
              const [startDate, endDate] = dueDate.split(',');
              conditions.push(`DATE(t.due_date) >= $${paramIndex} AND DATE(t.due_date) <= $${paramIndex + 1}`);
              values.push(startDate.trim(), endDate.trim());
              paramIndex += 2;
            } else {
              conditions.push(`DATE(t.due_date) = $${paramIndex}`);
              values.push(dueDate);
              paramIndex++;
            }
          }
          
          // 验证排序字段
          const validSortFields = ['created_at', 'updated_at', 'due_date', 'priority', 'title'];
          const finalSortBy = validSortFields.includes(sortBy) ? sortBy : 'created_at';
          
          // 构建SQL查询
          const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
          const orderClause = `ORDER BY t.${finalSortBy} DESC`;
          const limitClause = `LIMIT $${paramIndex}`;
          
          values.push(limit);
          
          const query = `
            SELECT t.*, 
                   COALESCE(
                     json_agg(
                       CASE WHEN s.id IS NOT NULL THEN 
                         json_build_object('id', s.id, 'title', s.title, 'completed', s.completed)
                       END
                     ) FILTER (WHERE s.id IS NOT NULL), 
                     '[]'
                   ) as subtasks
            FROM tasks t
            LEFT JOIN subtasks s ON t.id = s.task_id
            ${whereClause}
            GROUP BY t.id
            ${orderClause}
            ${limitClause}
          `;
          
          console.log('[LangChain] 🔍 执行SQL查询:', query);
          console.log('[LangChain] 📊 查询参数:', values);
          
          // 执行查询
          const result = await this.db.query(query, values);
          
          // 转换字段名格式
          const tasks = result.rows.map((row: any) => {
            const { 
              due_date, created_at, updated_at, user_id,
              is_recurring, recurring_type, recurring_pattern, parent_recurring_id,
              ...cleanRow 
            } = row;
            
            return {
              ...cleanRow,
              dueDate: due_date,
              createdAt: created_at,
              updatedAt: updated_at,
              userId: user_id,
              isRecurring: is_recurring,
              recurringType: recurring_type,
              recurringPattern: recurring_pattern,
              parentRecurringId: parent_recurring_id
            };
          });
          
          // 获取总数（用于分页）
          const countQuery = `
            SELECT COUNT(*) as total
            FROM tasks t
            ${whereClause}
          `;
          const countResult = await this.db.query(countQuery, values.slice(0, -1)); // 排除limit
          const total = parseInt(countResult.rows[0].total);
          
          const response = {
            success: true,
            data: {
              tasks,
              total,
              returned: tasks.length,
              limit,
              hasMore: tasks.length === limit
            },
            message: `找到${tasks.length}个任务，共${total}个`
          };
          
          console.log('[LangChain] ✅ 查询任务成功');
          console.log('[LangChain] 📊 查询结果:', {
            total,
            returned: tasks.length,
            hasMore: response.data.hasMore
          });
          return JSON.stringify(response);
        } catch (error) {
          console.error('[LangChain] ❌ 查询任务失败:', error);
          console.error('[LangChain] ❌ 错误堆栈:', error instanceof Error ? error.stack : 'No stack trace');
          
          const errorResponse = {
            success: false,
            error: error instanceof Error ? error.message : '查询任务失败'
          };
          
          console.log('[LangChain] 📤 错误响应:', JSON.stringify(errorResponse, null, 2));
          return JSON.stringify(errorResponse);
        }
      },
      {
        name: "query_tasks",
        description: "查询任务列表",
        schema: z.object({
          filters: z.object({
            status: z.string().optional().describe("任务状态: todo, in_progress, review, done"),
            priority: z.string().optional().describe("优先级: P0, P1, P2, P3"),
            category: z.string().optional().describe("分类: work, personal, learning, health, other"),
            completed: z.boolean().optional().describe("是否完成"),
            tags: z.array(z.string()).optional().describe("任务标签数组"),
            dueDate: z.string().optional().describe("截止日期: YYYY-MM-DD 或 YYYY-MM-DD,YYYY-MM-DD (范围)")
          }).optional().describe("过滤条件"),
          sortBy: z.string().optional().describe("排序字段: created_at, updated_at, due_date, priority, title"),
          limit: z.number().optional().describe("返回数量限制，默认20")
        })
      }
    );
  }

  // 完成任务工具
  private completeTaskTool() {
    return tool(
      async (input: any) => {
        const { taskId, notes } = input;
        try {
          console.log(`[LangChain] 完成任务: ${taskId}`);
          
          const result = await this.db.query(`
            UPDATE tasks 
            SET status = 'done', completed = true, updated_at = $1
            WHERE id = $2 AND user_id = $3
            RETURNING *
          `, [normalizeTimestamp(new Date()), taskId, 'default-user']);

          if (result.rows.length === 0) {
            return JSON.stringify({
              success: false,
              error: '任务不存在'
            });
          }

          const task = result.rows[0];
          
          return JSON.stringify({
            success: true,
            data: task,
            message: `已完成任务"${task.title}"`
          });
        } catch (error) {
          console.error('[LangChain] 完成任务失败:', error);
          return JSON.stringify({
            success: false,
            error: error instanceof Error ? error.message : '完成任务失败'
          });
        }
      },
      {
        name: "complete_task",
        description: "标记任务为完成",
        schema: z.object({
          taskId: z.string().describe("任务ID"),
          notes: z.string().optional().describe("完成备注")
        })
      }
    );
  }

  // 删除任务工具
  private deleteTaskTool() {
    return tool(
      async (input: any) => {
        const { taskId } = input;
        try {
          console.log(`[LangChain] 删除任务: ${taskId}`);
          
          const result = await this.db.query(`
            DELETE FROM tasks 
            WHERE id = $1 AND user_id = $2
            RETURNING *
          `, [taskId, 'default-user']);

          if (result.rows.length === 0) {
            return JSON.stringify({
              success: false,
              error: '任务不存在'
            });
          }

          const task = result.rows[0];
          
          return JSON.stringify({
            success: true,
            data: task,
            message: `已删除任务"${task.title}"`
          });
        } catch (error) {
          console.error('[LangChain] 删除任务失败:', error);
          return JSON.stringify({
            success: false,
            error: error instanceof Error ? error.message : '删除任务失败'
          });
        }
      },
      {
        name: "delete_task",
        description: "删除任务",
        schema: z.object({
          taskId: z.string().describe("任务ID")
        })
      }
    );
  }

  // 获取任务统计工具
  private getTaskStatsTool() {
    return tool(
      async (input: any) => {
        const { period } = input;
        try {
          console.log(`[LangChain] 获取任务统计: ${period}`);
          
          let dateFilter = '';
          const values = ['default-user'];
          let paramIndex = 2;

          switch (period) {
            case 'today':
              dateFilter = `AND DATE(created_at) = CURRENT_DATE`;
              break;
            case 'week':
              dateFilter = `AND created_at >= CURRENT_DATE - INTERVAL '7 days'`;
              break;
            case 'month':
              dateFilter = `AND created_at >= CURRENT_DATE - INTERVAL '30 days'`;
              break;
            default:
              dateFilter = '';
          }

          const result = await this.db.query(`
            SELECT 
              COUNT(*) as total,
              COUNT(CASE WHEN status = 'todo' THEN 1 END) as todo,
              COUNT(CASE WHEN status = 'in_progress' THEN 1 END) as in_progress,
              COUNT(CASE WHEN status = 'review' THEN 1 END) as review,
              COUNT(CASE WHEN status = 'done' THEN 1 END) as done,
              COUNT(CASE WHEN completed = true THEN 1 END) as completed
            FROM tasks 
            WHERE user_id = $1 ${dateFilter}
          `, values);

          const stats = result.rows[0];
          
          return JSON.stringify({
            success: true,
            data: {
              period,
              total: parseInt(stats.total),
              todo: parseInt(stats.todo),
              in_progress: parseInt(stats.in_progress),
              review: parseInt(stats.review),
              done: parseInt(stats.done),
              completed: parseInt(stats.completed)
            },
            message: `获取${period}期间的任务统计`
          });
        } catch (error) {
          console.error('[LangChain] 获取任务统计失败:', error);
          return JSON.stringify({
            success: false,
            error: error instanceof Error ? error.message : '获取任务统计失败'
          });
        }
      },
      {
        name: "get_task_stats",
        description: "获取任务统计信息",
        schema: z.object({
          period: z.enum(["today", "week", "month", "all"]).optional().describe("统计周期")
        })
      }
    );
  }

  // 转换消息格式
  private convertMessages(messages: any[]): BaseMessage[] {
    return messages.map(msg => {
      switch (msg.role) {
        case 'user':
          return new HumanMessage(msg.content);
        case 'assistant':
          return new AIMessage(msg.content);
        case 'system':
          return new SystemMessage(msg.content);
        default:
          return new HumanMessage(msg.content);
      }
    });
  }

  // 流式聊天
  async *streamChat(messages: any[], userId?: string): AsyncGenerator<any, void, unknown> {
    try {
      console.log('[LangChain] 🚀 开始流式聊天');
      console.log('[LangChain] 📥 输入消息:', JSON.stringify(messages, null, 2));
      console.log('[LangChain] 👤 用户ID:', userId);
      
      // 设置当前用户ID，供工具使用
      this.currentUserId = userId;
      
      const langchainMessages = this.convertMessages(messages);
      console.log('[LangChain] 🔄 转换后的消息:', JSON.stringify(langchainMessages, null, 2));
      
      console.log('[LangChain] 🔗 开始调用模型流式接口...');
      const stream = await this.modelWithTools.stream(langchainMessages);
      console.log('[LangChain] ✅ 模型流式接口调用成功');

      let hasToolCalls = false;
      let toolCalls: any[] = [];
      let chunkCount = 0;

      console.log('[LangChain] 📡 开始处理流式数据...');
      for await (const chunk of stream) {
        chunkCount++;
        console.log(`[LangChain] 📦 处理第${chunkCount}个chunk:`, JSON.stringify(chunk, null, 2));
        
        // 处理内容增量
        if (chunk.content) {
          console.log(`[LangChain] 📝 内容增量: "${chunk.content}"`);
          yield {
            type: 'content',
            content: chunk.content
          };
        }

        // 收集工具调用
        if (chunk.tool_calls && chunk.tool_calls.length > 0) {
          console.log(`[LangChain] 🔧 发现工具调用:`, JSON.stringify(chunk.tool_calls, null, 2));
          hasToolCalls = true;
          toolCalls.push(...chunk.tool_calls);
        }
      }
      
      console.log(`[LangChain] 📊 流式数据处理完成，共处理${chunkCount}个chunk`);
      console.log(`[LangChain] 🔧 工具调用状态: hasToolCalls=${hasToolCalls}, toolCalls.length=${toolCalls.length}`);

      // 如果有工具调用，执行它们
      if (hasToolCalls && toolCalls.length > 0) {
        console.log('[LangChain] 🚀 开始执行工具调用...');
        const toolResults = [];
        
        for (let i = 0; i < toolCalls.length; i++) {
          const toolCall = toolCalls[i];
          
          // 跳过空的工具调用
          if (!toolCall.name || toolCall.name.trim() === '') {
            console.log(`[LangChain] ⚠️ 跳过空工具调用: ${toolCall.id}`);
            continue;
          }
          
          console.log(`[LangChain] 🔧 执行第${i + 1}个工具调用:`, JSON.stringify(toolCall, null, 2));
          
          yield {
            type: 'tool_call',
            toolCall: {
              name: toolCall.name,
              arguments: toolCall.args,
              id: toolCall.id
            }
          };

          // 执行工具
          try {
            console.log(`[LangChain] 🔍 查找工具: ${toolCall.name}`);
            const tool = this.tools.find((t: any) => t.name === toolCall.name);
            if (tool) {
              console.log(`[LangChain] ✅ 找到工具，开始执行...`);
              const result = await tool.invoke(toolCall.args);
              console.log(`[LangChain] ✅ 工具执行成功，结果:`, result);
              
              toolResults.push({
                name: toolCall.name,
                result: result,
                id: toolCall.id
              });
              
              yield {
                type: 'tool_result',
                toolResult: {
                  name: toolCall.name,
                  result: result,
                  id: toolCall.id
                }
              };
            } else {
              console.error(`[LangChain] ❌ 未找到工具: ${toolCall.name}`);
              console.log(`[LangChain] 📋 可用工具列表:`, this.tools.map(t => t.name));
              
              toolResults.push({
                name: toolCall.name,
                error: `未找到工具: ${toolCall.name}`,
                id: toolCall.id
              });
              
              yield {
                type: 'tool_error',
                toolError: {
                  name: toolCall.name,
                  error: `未找到工具: ${toolCall.name}`,
                  id: toolCall.id
                }
              };
            }
          } catch (error) {
            console.error(`[LangChain] ❌ 工具执行错误:`, error);
            console.error(`[LangChain] ❌ 错误堆栈:`, error instanceof Error ? error.stack : 'No stack trace');
            
            toolResults.push({
              name: toolCall.name,
              error: error instanceof Error ? error.message : '工具执行失败',
              id: toolCall.id
            });
            
            yield {
              type: 'tool_error',
              toolError: {
                name: toolCall.name,
                error: error instanceof Error ? error.message : '工具执行失败',
                id: toolCall.id
              }
            };
          }
        }
        console.log('[LangChain] ✅ 所有工具调用执行完成');
        
        // 工具调用完成后，生成一个简单的回复
        console.log('[LangChain] 🔄 生成工具调用完成回复...');
        try {
          // 基于工具结果生成回复
          const successResults = toolResults.filter(tr => !tr.error);
          const errorResults = toolResults.filter(tr => tr.error);
          
          let responseContent = '';
          if (successResults.length > 0) {
            responseContent = `已成功执行${successResults.length}个工具调用。`;
            if (successResults.some(tr => tr.name === 'query_tasks')) {
              responseContent += ' 查询到任务数据，请查看上方的工具执行结果。';
            }
          }
          if (errorResults.length > 0) {
            responseContent += ` 有${errorResults.length}个工具调用失败。`;
          }
          
          if (responseContent) {
            console.log(`[LangChain] 📝 生成回复内容: "${responseContent}"`);
            yield {
              type: 'content',
              content: responseContent
            };
          }
          
          console.log('[LangChain] ✅ 工具调用完成回复生成完成');
        } catch (error) {
          console.error(`[LangChain] ❌ 生成回复失败:`, error);
          console.error(`[LangChain] ❌ 错误堆栈:`, error instanceof Error ? error.stack : 'No stack trace');
          yield {
            type: 'error',
            error: error instanceof Error ? error.message : '生成回复失败'
          };
        }
      }
      
      console.log('[LangChain] 🎉 流式聊天完成');
    } catch (error) {
      console.error(`[LangChain] ❌ 流式聊天错误:`, error);
      console.error(`[LangChain] ❌ 错误堆栈:`, error instanceof Error ? error.stack : 'No stack trace');
      
      yield {
        type: 'error',
        error: error instanceof Error ? error.message : '聊天失败'
      };
    }
  }

  // 非流式聊天
  async chat(messages: any[], userId?: string): Promise<any> {
    try {
      console.log('[LangChain] 🚀 开始非流式聊天');
      console.log('[LangChain] 📥 输入消息:', JSON.stringify(messages, null, 2));
      console.log('[LangChain] 👤 用户ID:', userId);
      
      const langchainMessages = this.convertMessages(messages);
      console.log('[LangChain] 🔄 转换后的消息:', JSON.stringify(langchainMessages, null, 2));
      
      console.log('[LangChain] 🔗 开始调用模型接口...');
      const response = await this.modelWithTools.invoke(langchainMessages);
      console.log('[LangChain] ✅ 模型接口调用成功');
      console.log('[LangChain] 📤 模型响应:', JSON.stringify(response, null, 2));
      
      // 处理工具调用
      if (response.tool_calls && response.tool_calls.length > 0) {
        console.log(`[LangChain] 🔧 发现${response.tool_calls.length}个工具调用`);
        const toolResults = [];
        
        for (let i = 0; i < response.tool_calls.length; i++) {
          const toolCall = response.tool_calls[i];
          console.log(`[LangChain] 🔧 执行第${i + 1}个工具调用:`, JSON.stringify(toolCall, null, 2));
          
          try {
            // 找到对应的工具
            console.log(`[LangChain] 🔍 查找工具: ${toolCall.name}`);
            const tool = this.tools.find((t: any) => t.name === toolCall.name);
            if (tool) {
              console.log(`[LangChain] ✅ 找到工具，开始执行...`);
              const result = await tool.invoke(toolCall.args);
              console.log(`[LangChain] ✅ 工具执行成功，结果:`, result);
              
              toolResults.push({
                name: toolCall.name,
                result: result,
                id: toolCall.id
              });
            } else {
              console.error(`[LangChain] ❌ 未找到工具: ${toolCall.name}`);
              console.log(`[LangChain] 📋 可用工具列表:`, this.tools.map(t => t.name));
              
              toolResults.push({
                name: toolCall.name,
                error: `未找到工具: ${toolCall.name}`,
                id: toolCall.id
              });
            }
          } catch (error) {
            console.error(`[LangChain] ❌ 工具执行错误:`, error);
            console.error(`[LangChain] ❌ 错误堆栈:`, error instanceof Error ? error.stack : 'No stack trace');
            
            toolResults.push({
              name: toolCall.name,
              error: error instanceof Error ? error.message : '工具执行失败',
              id: toolCall.id
            });
          }
        }
        
        console.log('[LangChain] ✅ 所有工具调用执行完成');
        const finalResponse = {
          content: response.content,
          tool_calls: response.tool_calls,
          tool_results: toolResults
        };
        console.log('[LangChain] 📤 最终响应:', JSON.stringify(finalResponse, null, 2));
        return finalResponse;
      }
      
      const finalResponse = {
        content: response.content,
        tool_calls: response.tool_calls || []
      };
      console.log('[LangChain] 📤 最终响应:', JSON.stringify(finalResponse, null, 2));
      return finalResponse;
    } catch (error) {
      console.error('[LangChain] ❌ 聊天失败:', error);
      console.error('[LangChain] ❌ 错误堆栈:', error instanceof Error ? error.stack : 'No stack trace');
      throw new Error(error instanceof Error ? error.message : '聊天失败');
    }
  }
}

// 导出单例实例
export const langchainService = new LangChainService();
